package router

import (
	"time"

	"coupons/router/middleware"
	"coupons/service"

	"github.com/gin-contrib/cors"
	"github.com/gin-gonic/gin"
)

// SetupRouter 配置路由
func SetupRouter(seckillService *service.SeckillService, wsHub *service.Hub) *gin.Engine {
	r := gin.Default()

	// ✅ 全局 CORS 中间件
	r.Use(cors.New(cors.Config{
		AllowOrigins:     []string{"http://localhost:63342"}, // 前端调试地址
		AllowMethods:     []string{"GET", "POST", "PUT", "DELETE", "OPTIONS"},
		AllowHeaders:     []string{"Origin", "Content-Type", "Authorization"},
		ExposeHeaders:    []string{"Content-Length"},
		AllowCredentials: true,
		MaxAge:           12 * time.Hour,
	}))

	// 健康检查
	r.GET("/health", func(c *gin.Context) {
		c.JSON(200, gin.H{
			"status": "ok",
			"time":   time.Now(),
		})
	})

	// API路由组
	api := r.Group("/api/v1")
	{
		// 优惠券相关
		voucher := api.Group("/vouchers")
		{
			// 查询所有优惠券
			voucher.GET("", seckillService.GetVouchers)
			// 根据 优惠券id 查询单张优惠券
			voucher.GET("/:voucher_id", seckillService.GetVoucherByVoucherId)
			// 根据 优惠券id 查询单张
			voucher.GET("/:voucher_id/stock", seckillService.GetVoucherStock)
		}

		// 秒杀相关（需要JWT认证）
		seckill := api.Group("/seckill")
		seckill.Use(middleware.JWTAuth())
		{
			// 秒杀
			seckill.POST("", seckillService.Seckill)
			// 获取用户订单
			seckill.GET("/orders", seckillService.GetUserOrders)
			// 获取订单详情
			seckill.GET("/orders/:voucher_id", seckillService.GetOrderByVoucherId)
			// 更新优惠券使用状态
			seckill.PUT("/vouchers/:voucher_id/use", seckillService.UseVoucher)
		}
	}

	// WebSocket路由
	r.GET("/ws", func(c *gin.Context) {
		service.HandleWebSocket(wsHub, c)
	})

	return r
}
